package com.sdp.right.control;


import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.db.sys_emp_leave.service.ISysEmpLeaveService;
import com.sdp.right.entity.SysEmpLeave;
import com.sdp.right.flow.dto.FlowParam;
import com.sdp.right.flow.service.ISysFlowService;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-07-17
 */
@RestController
@RequestMapping("/SysEmpLeaveController")
public class SysEmpLeaveController {

	@Autowired
	private ISysEmpLeaveService iSysEmpLeaveService;
	
	@Autowired
	private ISysFlowService iSysFlowService;
	
	@Autowired
	private Query query;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iSysEmpLeaveService, SysEmpLeave.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	public Result<?> save(@RequestBody JSONObject obj) {
		SysEmpLeave empLeave = obj.getObject("empLeave", SysEmpLeave.class);
		FlowParam flowParam =  obj.getObject("flowParam", FlowParam.class);
		if(StringUtils.isEmpty(empLeave.getKeyId())) {
			String instanceId = iSysFlowService.startUpFlow(flowParam);
			empLeave.setInstanceId(instanceId);
			iSysEmpLeaveService.save(empLeave);
		}else {
			iSysEmpLeaveService.updateById(empLeave);
		}
		return Result.ok(empLeave);
	}
	
	@PostMapping(value = "/commit")
	public Result<?> commit(@RequestBody JSONObject obj) {
		SysEmpLeave empLeave = obj.getObject("empLeave", SysEmpLeave.class);
		FlowParam flowParam =  obj.getObject("flowParam", FlowParam.class);
		Map<String,String> variable = new HashMap<>();
		variable.put("pass", flowParam.getPass());
		flowParam.setVariable(variable);
		BusinessContext businessContext = iSysFlowService.comitFlow(flowParam);
		if(businessContext.isSuccess()) {
			iSysEmpLeaveService.updateById(empLeave);
		}
		return Result.ok(empLeave);
	}
	
	@GetMapping(value = "/queryEmpLeaveByInstanceId")
	public Result<?> queryEmpLeaveByInstanceId(@RequestParam(name="instanceId",required=true) String instanceId) {
		if(StringUtils.isEmpty(instanceId)) {
			return Result.error("任务信息不存在");
		}
		return Result.ok(iSysEmpLeaveService.queryEmpLeaveByInstanceId(instanceId));
	}
	
}

